package com.lagou.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lagou.pojo.DeepSeekRequest;
import com.lagou.pojo.DeepSeekResponse;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DeepSeekService {

    @Value("${deepseek.api.url}")
    private String url;

    @Value("${deepseek.api.model}")
    private String model;

    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

    public String chat(String question) throws IOException {

        DeepSeekRequest requestBody = DeepSeekRequest.builder()
                .model(model)
                .prompt(question)
                .build();
        // 创建HTTP请求
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(requestBody)))
                .build();
        // 发送请求并处理响应
        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                DeepSeekResponse deepSeekResponse = JSONObject.parseObject(line, DeepSeekResponse.class);
                sb.append(deepSeekResponse.getResponse());
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "服务器繁忙！";
    }
}
